<template>
    <el-dialog v-model="DialogShow" width="30%" title="添加题库" center custom-class="custom_class ">
        <div class="main">
            <el-form :model="form" ref="ruleFormRef" label-width="auto" style="max-width: 600px" :rules="ruleForm">
                <el-form-item label="题库类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择" @change="changeType">
                        <el-option label="单选" :value="0" />
                        <el-option label="多选" :value="1" />
                        <el-option label="判断" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分值" prop="score">
                    <el-input-number v-model="form.score" :min="1" :max="10" />
                </el-form-item>
                <el-form-item label="题干" prop="questionContent">
                    <el-input v-model="form.questionContent" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label="选项" prop="optionsInfoDtos">
                    <div class="determine" v-if="form.type == '2'">
                        <div class="determine_item">
                            <span class="determine_item_option">A.</span>
                            <span class="determine_item_content">正确</span>
                        </div>
                        <div class="determine_item">
                            <span class="determine_item_option">B.</span>
                            <span class="determine_item_content">错误</span>
                        </div>
                    </div>
                    <div class="Radio" v-else>
                        <div class="determine_item" v-for="item, index in options" :key="item.title">
                            <span class="determine_item_option">{{ item.title }}.</span>
                            <el-input v-model="item.content" placeholder="请输入" clearable />
                            <div class="determine_item_btn">
                                <el-button :icon="Plus" circle @click="addOptions"
                                    v-if="chooseOptions.length > options.length" />
                                <el-button type="danger" :icon="Delete" circle @click="deleteOptions(index)"
                                    v-if="options.length != 1" />
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="标答" prop="answer">
                    <div class="determine" v-if="form.type == '2'">
                        <el-radio-group v-model="form.answer" class="ml-4">
                            <el-radio label="A" size="large">A</el-radio>
                            <el-radio label="B" size="large">B</el-radio>
                        </el-radio-group>
                    </div>
                    <template v-if="form.type == '0'">
                        <el-radio-group v-model="form.answer">
                            <el-radio size="large" v-for="(item, index) in options" :label="item.title" :key="index">{{
        item.title
    }}</el-radio>
                        </el-radio-group>
                    </template>
                    <div class="multiple_choice" v-if="form.type == '1'">
                        <el-checkbox-group v-model="form.answers">
                            <el-checkbox :label="item.title" :value="item.title" v-for="item, index in options"
                                :key="index" />
                        </el-checkbox-group>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="DialogShow = false">取消</el-button>
                <el-button type="primary" @click="submitForm"> 确定 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';


import {
    Delete,
    Plus
} from '@element-plus/icons-vue'
import { ElMessage } from "element-plus";

const props = defineProps(['show', 'questionBankId', 'editInfo'])
const emit = defineEmits(['update:show', 'update:editInfo'])

import useUserInfo from "store/useUserInfo.js";
const useUserInfoStore = useUserInfo();
import { storeToRefs } from 'pinia'
const { userInfo } = storeToRefs(useUserInfoStore)

import { addQuestionApi1, editQuestionApi } from "@/api/index";

const DialogShow = ref(false)
// 收集选项
const options = reactive([
    {
        title: 'A',
        content: null
    },
    {
        title: 'B',
        content: null
    },
])
// 是否编辑表单
const isEdit = ref(false)
// 初始化表单
const initForm = () => {
    isEdit.value = true;
    console.log("编辑表单", props.editInfo);
    const { answers, id, score, optionsInfoDtos, questionContent, type } = props.editInfo
    Object.assign(form, { answers, answer: answers[0], score, id, optionsInfoDtos, questionContent, type })
    // 遍历生成选项
    options.splice(0)
    for (let i = 0; i < optionsInfoDtos.length; i++) {
        options.unshift({
            title: optionsInfoDtos[i].options,
            content: optionsInfoDtos[i].optionsContent
        })
    }
}

watch(() => props.show, (newVal) => {
    console.log(newVal, 'newVal');
    if (!newVal) {
        form.questionContent = "";
        form.type = '0';
        form.score = 1;
        form.answers = [];
        form.answer = null;
        options.map((item) => {
            item.content = "";
        })
        emit("update:editInfo", null);
        options.splice(1);
        isEdit.value = false;
    }
    newVal && props.editInfo && initForm();
    DialogShow.value = newVal;
});
watch(() => DialogShow.value, (newVal) => {
    emit('update:show', newVal);
});

// 数据收集
const form = reactive({
    questionContent: '',
    type: 0,
    score: 1,
    answers: [],
    answer: '',
    optionsInfoDtos: null,
})


const chooseOptions = ['A', 'B', 'C', 'D', 'E', 'F']

// 添加选项
const addOptions = () => {
    const index = options.length;
    options.push({
        title: chooseOptions[index],
        content: null
    })
}
// 删除选项
const deleteOptions = (index) => {
    options.splice(index, 1)
    options.forEach((item, idx) => {
        item.title = chooseOptions[idx]
    })
}

// 类型切换
const changeType = () => {
    form.answer = null;
    form.answers = [];

}
// 选项验证
const checkOptionsInfoDtos = (rule, value, callback) => {
    if (form.type == '2') {
        callback()
        return
    }
    options.some(option => {
        if (option.content == null) {
            callback(new Error('选项不能为空'));
            return true;
        }
        callback()
        return false;
    })
}
// 标答验证
const checkAnswer = (rule, value, callback) => {
    if (form.type == '1' && form.answers.length == 0) {
        callback(new Error('答案不能为空'));
    }
    if (form.type == '2' || form.type == '0') {
        if (!form.answer) {
            callback(new Error('答案不能为空'));
        }
    }
    callback();
}
// 表单验证
const ruleForm = reactive({
    questionContent: [
        { required: true, message: '请输入题库名称', trigger: 'blur' },
        { min: 4, max: 100, message: '名称在4到100个字', trigger: 'blur' },
    ],
    optionsInfoDtos: [{ validator: checkOptionsInfoDtos, trigger: 'blur' }],
    answer: [{ validator: checkAnswer, trigger: 'blur' }],
})
const ruleFormRef = ref(null);
const submitForm = async () => {
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            console.log('submit!', form, options)
            const params = {
                type: form.type,
                score: form.score,
                questionBankId: props.questionBankId,
                questionContent: form.questionContent,
                operatorId: userInfo.value.userId,
            }
            if (form.type == '0' || form.type == '2') {
                params.answers = [form.answer]
            } else if (form.type == '1') {
                params.answers = form.answers
            }
            if (form.type == '2') {
                params.optionsInfoDtos = [
                    {
                        optionsContent: '正确',
                        options: 'A'
                    },
                    {
                        optionsContent: '错误',
                        options: 'B'
                    }
                ]
            } else {
                params.optionsInfoDtos = options.map((item, index) => {
                    return {
                        optionsContent: item.content,
                        options: item.title
                    }
                })
            }
            let res = null
            if (!isEdit.value) {
                res = await addQuestionApi1(params)
            } else {
                delete params.questionBankId
                res = await editQuestionApi(form.id, params)
            }
            if (res.code !== "10000") {
                ElMessage({
                    showClose: true,
                    message: res.message,
                    type: "error",
                });
                return;
            }
            ElMessage({
                showClose: true,
                message: `${isEdit.value ? '编辑' : '新增'}成功!`,
                type: "success",
            });
            emit('update:show', false);
            emit('onSubmit');
        } else {
            console.log('error submit!', fields)
        }
    })
}




</script>

<style lang="scss">
.determine,
.Radio {
    .determine_item {
        display: flex;
        align-items: center;
        margin: 5px 0;

        .determine_item_option {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            /* margin-top: 10px; */
            height: 30px;
            line-height: 30px;
            text-align: center;
        }

        .determine_item_btn {
            display: flex;
            align-items: center;
            margin-left: 50px;
        }

        .determine_item_content {
            font-size: 14px;
            color: #333;
            margin-top: 10px;
            height: 30px;
            line-height: 30px;
            text-align: center;
        }
    }
}
</style>
